package com.tian.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tian.common.CommonResult;
import com.tian.common.PageResult;
import com.tian.dto.ChargeUserLoginResDto;
import com.tian.dto.PayOrderQueryReqDto;
import com.tian.dto.PayOrderQueryRespDto;
import com.tian.entity.ChargePayOrder;
import com.tian.mapper.ChargePayOrderMapper;
import com.tian.service.PayOrderQueryService;
import com.tian.util.DateUtils;
import com.tian.util.UserCacheUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * {@code @description:} 我的充值订单信息查询服务实现类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-12-03 9:50
 * {@code @version:} 1.0
 */
@Service
public class PayOrderQueryServiceImpl implements PayOrderQueryService {
    @Resource
    private ChargePayOrderMapper chargePayOrderMapper;
    @Override
    public CommonResult<PageResult<List<PayOrderQueryRespDto>>> query(PayOrderQueryReqDto payOrderQueryReqDto) {
        ChargeUserLoginResDto user = UserCacheUtil.getUser();
        Long userId = user.getId();
        int status = payOrderQueryReqDto.getStatus();
        Page<ChargePayOrder> page = PageHelper.startPage(payOrderQueryReqDto.getCurrentPage(), payOrderQueryReqDto.getPageSize());
        List<ChargePayOrder> chargePayOrders = chargePayOrderMapper.selectByUserIdAndStatus(userId, status);
        List<PayOrderQueryRespDto> payOrderQueryRespDtoList = new ArrayList<>();
        chargePayOrders.forEach(chargePayOrder -> {
            PayOrderQueryRespDto payOrderQueryRespDto = new PayOrderQueryRespDto();
            payOrderQueryRespDto.setId(chargePayOrder.getId());
            payOrderQueryRespDto.setOrderNo(chargePayOrder.getOrderNo());
            payOrderQueryRespDto.setActualAmount(chargePayOrder.getAmount().toString());
            payOrderQueryRespDto.setTotalAmount(chargePayOrder.getAmount().add(chargePayOrder.getDiscountAmount()).toString());
            payOrderQueryRespDto.setPayTime(DateUtils.format(chargePayOrder.getUpdateTime(), DateUtils.FORMAT_SECOND));
            payOrderQueryRespDtoList.add(payOrderQueryRespDto);
        });
        PageResult<List<PayOrderQueryRespDto>> pageResult =  PageResult.setData((int)page.getTotal(), payOrderQueryReqDto.getPageSize(),
                page.getPages(), payOrderQueryReqDto.getCurrentPage(), payOrderQueryRespDtoList);
        return CommonResult.success(pageResult);
    }
}
